package com.yanqu.road.entity.systemgroup.rank;

import java.util.Comparator;
import java.util.LinkedList;

public class ServerRankModel {

    private LinkedList<ServerRank> rankList = new LinkedList<>();

    private Comparator sort = new ServerRankSort();

    private int rankNum = 2000;

    public ServerRankModel() {

    }

    public ServerRankModel(int rankNum) {
        this.rankNum = rankNum;
    }

    public void setRankList(LinkedList<ServerRank> rankList) {
        synchronized (this) {
            this.rankList = new LinkedList<>(rankList);
            this.rankList.sort(sort);
            while (this.rankList.size() > rankNum){
                this.rankList.removeLast();
            }
        }
    }

    public int getMyRank(long serverId) {
        int rank = -1;
        int index = 0;
        synchronized (this) {
            for(ServerRank serverRank : rankList){
                if(serverRank.getServerId() == serverId){
                    rank = index + 1;
                    break;
                }
                index++;
            }
        }
        if(rank > rankNum){
            rank = -1;
        }
        return rank;
    }

    public ServerRank getMyRankInfo(long serverId) {
        synchronized (this) {
            for(ServerRank serverRank: rankList){
                if(serverRank.getServerId() == serverId){
                    return serverRank;
                }
            }
        }
        return null;
    }

    /**
     * 添加到排行
     */
    public void rankChange(ServerRank serverRank) {
        boolean isChange = false;
        synchronized (this) {
            int size = rankList.size();
            ServerRank rank = getMyRankInfo(serverRank.getServerId());
            if(null != rank){
                rank.setLastUpdateTime(serverRank.getLastUpdateTime());
                rank.setValue(serverRank.getValue());
                isChange = true;
            }else {
                if (size < rankNum) {
                    rankList.add(serverRank);
                    isChange = true;
                } else if (rankList.getLast().getValue().compareTo(serverRank.getValue()) < 0) {
                    rankList.removeLast();
                    rankList.add(serverRank);
                    isChange = true;
                }
            }
            if(isChange) {
                rankList.sort(sort);
            }
        }
    }

    public LinkedList<ServerRank> getRankList() {
        return new LinkedList<>(rankList);
    }
}
